package com.ssyc.gsk_teacher.activity;

import android.content.Intent;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ssyc.common.base.BaseActivity;
import com.ssyc.common.base.BaseApplication;
import com.ssyc.common.base.Constants;
import com.ssyc.common.bean.BusInfo;
import com.ssyc.common.bean.ResultInfo;
import com.ssyc.common.http.HttpAdress;
import com.ssyc.common.http.HttpUtils;
import com.ssyc.common.manager.AccountUtils;
import com.ssyc.common.manager.PickChooseManager;
import com.ssyc.common.manager.PickerManager;
import com.ssyc.common.manager.StateBarManager;
import com.ssyc.common.utils.DateUtils;
import com.ssyc.common.utils.GsonUtil;
import com.ssyc.common.utils.MaxTextLengthFilter;
import com.ssyc.common.utils.SnackbarUtil;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.common.view.MyGridView;
import com.ssyc.common.view.dialog.CustomDialogManager;
import com.ssyc.gsk_teacher.R;
import com.ssyc.gsk_teacher.adapter.ShowPicGvAdapter;
import com.ssyc.gsk_teacher.adapter.TargetGvAdapter;
import com.ssyc.gsk_teacher.bean.ClassInfo;
import com.ssyc.gsk_teacher.bean.TargetInfo;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.iwf.photopicker.PhotoPicker;
import me.shaohui.advancedluban.Luban;
import me.shaohui.advancedluban.OnMultiCompressListener;
import okhttp3.Call;

/**
 * 发布活动界面
 * Created by Administrator on 2018/1/19 0019.
 */

public class TeacherSendEventActivity extends BaseActivity implements AdapterView.OnItemClickListener, View.OnClickListener {
    //活动主题
    private EditText etAction;
    private TextView tvStarttime;

    //选择开始时间的布局
    private LinearLayout llChooseStarttime;
    private TextView tvEndtime;

    //选择结束时间的布局
    private LinearLayout llChooseEndtime;
    //活动地点
    private EditText etAddress;

    //返回
    private RelativeLayout rlBack;

    //显示活动对象的GirdView
    private MyGridView mgvShowclass;

    //活动内容的输入框
    private EditText etContent;

    //监听活动内容输入框长度的文本
    private TextView tvShowNum;

    //显示选择图片的GridView
    private MyGridView gvShowpic;

    //发布
    private TextView tvSend;

    //活动开始时间
    private Date beginDate;
    private String beginTime;

    //活动结束时间
    private Date endDate;
    private String endTime;

    //保存图片的地址集合
    List<String> mPicPaths;

    //展示选择图片适配对象
    private ShowPicGvAdapter adapter;

    private LinearLayout llMain;

    //所有班级的列表
    private List<ClassInfo.ListBean> classInfos;
    private List<TargetInfo> targetInfos;

    @Override
    protected boolean isNeedShowTitle() {
        return false;
    }

    @Override
    protected String setTitleText() {
        return "";
    }

    @Override
    protected int getContentLayout() {
        return R.layout.teacher_activity_send_event;
    }

    @Override
    protected void init() {

        showContent();

        //配置状态栏颜色
        initStateColor();

        //获取所有班级的json数据
        initIntent();

        //初始化视图的方法
        initView();

        //设置监听的方法
        initListener();

        //设置展示活动对象的GridView
        initTargetGv();

        //设置展示图片GridView
        initPicGv();
    }


    /**
     * 初始化视图的方法
     */
    public void initView() {
        etAction = findViewById(R.id.et_action);
        tvStarttime = findViewById(R.id.tv_starttime);
        llChooseStarttime = findViewById(R.id.ll_choose_starttime);
        llChooseStarttime.setOnClickListener(this);
        tvEndtime = findViewById(R.id.tv_endtime);
        llChooseEndtime = findViewById(R.id.ll_choose_endtime);
        llChooseEndtime.setOnClickListener(this);
        etAddress = findViewById(R.id.et_address);
        mgvShowclass = findViewById(R.id.mgv_showclass);
        etContent = findViewById(R.id.et_content);
        tvShowNum = findViewById(R.id.tv_show_num);
        etContent.setFilters(new InputFilter[]{new MaxTextLengthFilter(101)});
        gvShowpic = findViewById(R.id.gv_showpic);
        llMain = findViewById(R.id.ll_main);
        tvSend = findViewById(R.id.tv_send);
        tvSend.setOnClickListener(this);
        rlBack = findViewById(R.id.rl_back);
        rlBack.setOnClickListener(this);
    }


    /**
     * 配置状态栏颜色的方法
     */
    private void initStateColor() {
        //设置6.0以后沉浸状体栏的问题
        StateBarManager.setBarWithUltimateBar(this, getResources().getColor(com.ssyc.common.R.color.titlebg),
                getResources().getColor(com.ssyc.common.R.color.nav_color));
    }

    /**
     * 获取所有的班级列表
     */
    private void initIntent() {
        String json = getIntent().getStringExtra("classinfos");
        if (!TextUtils.isEmpty(json)) {
            classInfos = GsonUtil.jsonToList(json, ClassInfo.ListBean[].class);
        }
    }


    /**
     * 给EditText设置监听的方法
     */
    private void initListener() {
        etContent.setFilters(new InputFilter[]{new MaxTextLengthFilter(501)});
        //输入框的改变监听
        etContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String inputText = etContent.getText().toString().trim();
                if (TextUtils.isEmpty(inputText)) {
                    tvShowNum.setText("0/500");
                } else {
                    if (inputText.length() > 501) {
                        tvShowNum.setText("500/500");
                    } else {
                        tvShowNum.setText(inputText.length() + "/500");
                    }
                }
            }
        });
    }


    /**
     * 设置选择活动对象的GridView
     */
    private void initTargetGv() {
        targetInfos = new ArrayList<>();
        for (int i = 0; i < classInfos.size(); i++) {
            TargetInfo info = new TargetInfo();
            info.className = classInfos.get(i).getName();
            info.isSelected = false;
            targetInfos.add(info);
        }
        TargetGvAdapter gvAdapter = new TargetGvAdapter(this, targetInfos, R.layout.teacher_gv_target);
        mgvShowclass.setAdapter(gvAdapter);
        mgvShowclass.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) {
                //条目的点击事件
                targetInfos.get(pos).isSelected = !targetInfos.get(pos).isSelected;
                gvAdapter.notifyDataSetChanged();
            }
        });
    }


    /**
     * 设置展示图片的GridView
     */
    private void initPicGv() {
        mPicPaths = new ArrayList<>();
        adapter = new ShowPicGvAdapter(this, mPicPaths);
        gvShowpic.setAdapter(adapter);
        gvShowpic.setOnItemClickListener(this);
    }


    /**
     * 页面控件的点击事件
     *
     * @param view
     */
    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.ll_choose_starttime) {
            //选择开始时间
            chooseTime(0);
        } else if (id == R.id.ll_choose_endtime) {
            //选择结束时间
            chooseTime(1);
        } else if (id == R.id.tv_send) {

            //防止连点
            if (UiUtils.isNotFastClick()) {
                //发布
            doUploading();
            }
        } else if (id == R.id.rl_back) {
            //返回
            finish();
        }
    }


    /**
     * 先判断添加的内容的完整性
     * 然后做图片上传的操作
     */
    private void doUploading() {

        //活动主题
        String action = etAction.getText().toString().trim();
        if (TextUtils.isEmpty(action)) {
            SnackbarUtil.ShortSnackbar(llBaseMain, "请输入活动主题", 0).show();
            return;
        }

        //活动时间
        if (TextUtils.isEmpty(beginTime)) {
            SnackbarUtil.ShortSnackbar(llBaseMain, "请选择活动开始时间", 0).show();
            return;
        }

        if (TextUtils.isEmpty(endTime)) {
            SnackbarUtil.ShortSnackbar(llBaseMain, "请选择活动结束时间", 0).show();
            return;
        }

        //判断活动结束时间是否大于起始时间
        long start = DateUtils.getTime(beginTime, "yyyy-M-dd HH:mm");
        long end = DateUtils.getTime(endTime, "yyyy-M-dd HH:mm");
        if (end < start) {
            SnackbarUtil.ShortSnackbar(llBaseMain, "活动的结束时间不能小于开始时间", 0).show();
            return;
        }

        //判断活动结束时间是否大于起始时间一个小时
        if ((end - start) < 60 * 60 * 1000) {
            SnackbarUtil.ShortSnackbar(llBaseMain, "活动的结束时间必须大于开始时间1个小时", 0).show();
            return;
        }

        //活动地点
        String address = etAddress.getText().toString().trim();
        if (TextUtils.isEmpty(address)) {
            SnackbarUtil.ShortSnackbar(llBaseMain, "请输入活动地点", 0).show();
            return;
        }

        //判断是否选择了活动对象
        if (!hasChoostTarget()) {
            SnackbarUtil.ShortSnackbar(llBaseMain, "未选择活动对象", 0).show();
            return;
        }

        //活动内容
        String content = etContent.getText().toString().trim();
        if (TextUtils.isEmpty(content)) {
            SnackbarUtil.ShortSnackbar(llBaseMain, "请输入活动内容", 0).show();
            return;
        }

        //判断是否选择了图片
//        if (mPicPaths == null || mPicPaths.size() == 0) {
//            SnackbarUtil.ShortSnackbar(llBaseMain, "请至少选择一张图片上传", 0).show();
//            return;
//        }

        CustomDialogManager.show(this, "上传中...");

        if (mPicPaths != null && mPicPaths.size() != 0) {

            //做压缩处理
            List<File> files = new ArrayList<>();
            for (int i = 0; i < mPicPaths.size(); i++) {
                File file = new File(mPicPaths.get(i));
                files.add(file);
            }

            //使用Luban做压缩图片处理
            Luban.compress(this, files).setMaxSize(150).setMaxHeight(1280).setMaxWidth(720).putGear(Luban.CUSTOM_GEAR).launch(new OnMultiCompressListener() {
                @Override
                public void onStart() {
                    //压缩开始
                }

                @Override
                public void onSuccess(List<File> compreFiles) {
                    //压缩成功后的回调,上传该集合的文件
                    doPostAction(compreFiles, action, address, content);
                }

                @Override
                public void onError(Throwable e) {
                    //压缩错误
                }
            });
        } else {
            //不需要上传图片
            doPostAction(null, action, address, content);
        }
    }

    /**
     * 上传服务器
     *
     * @param compreFiles
     * @param action
     * @param address
     * @param content
     */
    private void doPostAction(List<File> compreFiles, String action, String address, String content) {

        Map<String, String> map = new HashMap<>();

        map.put("acc", AccountUtils.getAccount(BaseApplication.context));

        map.put("role", AccountUtils.getRole(BaseApplication.context));

        map.put("apptoken", AccountUtils.getToken(BaseApplication.context));

        map.put("platform", "8");

        //活动主题
        map.put("tag", action);

        //开始时间
        map.put("begintime", beginTime);

        //结束时间
        map.put("endtime", endTime);

        //活动对象
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < targetInfos.size(); i++) {
            if (targetInfos.get(i).isSelected) {
                sb.append((i + 1) + ",");
            }
        }
        String target = sb.toString();

        map.put("target", target.substring(0, target.length() - 1));

        //活动地址
        map.put("address", address);

        //活动内容
        map.put("content", content);

        if (compreFiles != null && compreFiles.size() != 0) {
            //请求9号接口
            map.put("type", "9");
            //说明有图片
            Map<String, File> fileMap = new HashMap<>();
            for (int i = 0; i < compreFiles.size(); i++) {
                fileMap.put(System.currentTimeMillis() + i + i + ".jpg", compreFiles.get(i));
            }

            OkHttpUtils.post().url(HttpAdress.SENDEVENT).params(map).files("picture", fileMap).params(map).build().execute(new StringCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    UiUtils.Toast("服务器异常,上传失败", false);
                    CustomDialogManager.dissmiss();
                }

                @Override
                public void onResponse(String response, int id) {
                    Log.i("test", "返回的json是:" + response);
                    CustomDialogManager.dissmiss();
                    if (!TextUtils.isEmpty(response)) {
                        ResultInfo info = null;
                        try {
                            info = GsonUtil.jsonToBean(response, ResultInfo.class);
                        } catch (Exception e) {
                            Log.i("test", Constants.PARSEDATAERROR);
                        }
                        if (null != info) {
                            if ("200".equals(info.getState())) {
                                //返回成功
                                UiUtils.Toast("上传成功", false);
                                //上传成功后通知所有的活动界面和班级的活动界面进行刷新
                                BusInfo busInfo = new BusInfo();
                                busInfo.setType(TeacherEventActivity.UPDATASCORE);
                                EventBus.getDefault().post(busInfo);
                                finish();
                            } else {
                                UiUtils.Toast("上传失败,返回异常码是:" + info.getState(), false);
                                Log.i("test", Constants.ERRORSTATE + info.getState());
                            }
                        } else {
                            Log.i("test", Constants.EMPTY);
                        }
                    } else {
                        Log.i("test", Constants.EMPTY);
                    }
                }
            });
        } else {
            //没有图片请求19号接口
            map.put("type", "19");

            //没有图片
            HttpUtils.post(HttpAdress.SENDEVENT, map, this, new HttpUtils.CallBack() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    CustomDialogManager.dissmiss();
                    UiUtils.Toast("服务器异常,上传失败", false);
                }

                @Override
                public void onResponse(String response, int id) {
                    CustomDialogManager.dissmiss();
                    if (!TextUtils.isEmpty(response)) {
                        ResultInfo info = null;
                        try {
                            info = GsonUtil.jsonToBean(response, ResultInfo.class);
                        } catch (Exception e) {
                            Log.i("test", Constants.PARSEDATAERROR);
                        }
                        if (null != info) {
                            if ("200".equals(info.getState())) {
                                //返回成功
                                UiUtils.Toast("上传成功", false);
                                //上传成功后通知所有的活动界面和班级的活动界面进行刷新
                                BusInfo busInfo = new BusInfo();
                                busInfo.setType(TeacherEventActivity.UPDATASCORE);
                                EventBus.getDefault().post(busInfo);
                                finish();
                            } else {
                                UiUtils.Toast("上传失败,返回异常码是:" + info.getState(), false);
                                Log.i("test", Constants.ERRORSTATE + info.getState());
                            }
                        } else {
                            Log.i("test", Constants.EMPTY);
                        }
                    } else {
                        Log.i("test", Constants.EMPTY);
                    }
                }
            });
        }
    }

    /**
     * 判断是否选择了活动对象的方法
     *
     * @return
     */
    private boolean hasChoostTarget() {
        boolean res = false;
        if (null != targetInfos && targetInfos.size() != 0) {
            for (int i = 0; i < targetInfos.size(); i++) {
                if (targetInfos.get(i).isSelected) {
                    res = true;
                    break;

                }
            }
        }
        return res;
    }

    /**
     * 选择时间
     */
    private void chooseTime(final int type) {

        PickerManager.showPickerByLimit(type,this,new PickerManager.onSelectedListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                if(type==0){
                    //选择开始时间
                    beginDate = date;
                    beginTime = DateUtils.getTime(date, "yyyy-M-dd HH:mm");
                    tvStarttime.setText(beginTime);
                }else if(type==1){
                    //选择结束时间
                    endDate = date;
                    endTime = DateUtils.getTime(date, "yyyy-M-dd HH:mm");
                    tvEndtime.setText(endTime);
                }
            }
        });
    }


    /**
     * 展示图片的GridView的点击事件
     *
     * @param parent
     * @param view
     * @param position
     * @param l
     */
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long l) {
        Object itemAdapter = parent.getAdapter();
        if (itemAdapter instanceof ShowPicGvAdapter) {
            if (mPicPaths.size() != 9) {
                if (position == ((ShowPicGvAdapter) itemAdapter).getCount() - 1) {
                    PickChooseManager.startPhotoPickActivity(TeacherSendEventActivity.this, 9 - mPicPaths.size());
                } else {
                    PickChooseManager.startShowBigActivity(TeacherSendEventActivity.this, mPicPaths, position);
                }
            } else {
                PickChooseManager.startShowBigActivity(TeacherSendEventActivity.this, mPicPaths, position);
            }
        }
    }

    /**
     * 请求图库后的回调
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == PhotoPicker.REQUEST_CODE) {
            if (data != null) {
                ArrayList<String> photos =
                        data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);

                for (int i = 0; i < photos.size(); i++) {
                    mPicPaths.add(photos.get(i));
                }

                //通知适配器刷新
                adapter.notifyDataSetChanged();
            }
        }
    }

}
